package com.onetech.adrewards.free.activities;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.plus.PlusClient;
import com.onetech.adrewards.free.utils.CodeResults;
import com.onetech.adrewards.free.utils.MomentUtil;
import com.onetech.adrewards.free.R;

public class LoginActivity extends BaseActivity implements
		PlusClient.ConnectionCallbacks, PlusClient.OnConnectionFailedListener,
		PlusClient.OnAccessRevokedListener {

	private ProgressDialog _progressDialogAuthGoogleAcn = null;
	private ProgressDialog _progressDialogGetGooglePlayServices = null;
	private PlusClient _plusClient = null;
	private ConnectionResult _connectionResult = null;
	private static final int LOGIN_USING_GOOGLE_PLUS = 2;

	private int _usedLoginMethod = -1;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		socialConfig();
	}

	public void socialConfig() {
		try {
			// Google
			PlusClient.Builder plusClientBuilder = new PlusClient.Builder(this,
					this, this);
			_plusClient = plusClientBuilder.setActions(MomentUtil.ACTIONS)
					.build();
			// END: init services
		} catch (Exception e) {
			// ZID_Logger.error(ZID_Login.class.getName(),e.toString());
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.action_settings:
			_usedLoginMethod = LoginActivity.LOGIN_USING_GOOGLE_PLUS;

			int available = GooglePlayServicesUtil
					.isGooglePlayServicesAvailable(this);
			if (available != ConnectionResult.SUCCESS) {
				_progressDialogGetGooglePlayServices.show();
			} else {
				try {
					_connectionResult.startResolutionForResult(this, 1);
				} catch (Exception e) {
					_plusClient.connect();
				}
			}

			break;

		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (_usedLoginMethod) {
		case LOGIN_USING_GOOGLE_PLUS:
			if (requestCode == 1 || requestCode == 2) {
				if (resultCode != RESULT_OK) {
					return;
				}

				if (_plusClient.isConnected()) {
					return;
				}

				if (_plusClient.isConnecting()) {
					return;
				}

				_plusClient.connect();
			}
			break;
		default:
			break;
		}
	}

	// BEGIN: Google Callbacks
	@Override
	public void onAccessRevoked(ConnectionResult status) {
		if (!status.isSuccess()) {
			_plusClient.disconnect();
		}

		_plusClient.connect();
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		_connectionResult = result;
	}

	@Override
	public void onConnected(Bundle connectionHint) {
		_progressDialogAuthGoogleAcn.show();
		new AsyncTaskAuthenticateGoogleAcn().execute();
	}

	@Override
	public void onDisconnected() {
		_plusClient.connect();
	}

	class AsyncTaskAuthenticateGoogleAcn extends
			AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				String accountName = _plusClient.getAccountName();
				String scope = "oauth2:" + Scopes.PLUS_LOGIN;
				// String strToken = GoogleAuthUtil.getToken(ZID_Login.this,
				// accountName, scope);
				// String strResponse =
				// ZID_RestClient.requestAuthGoogleAcnURI(strToken);

				return "";
			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject jsonObject = new JSONObject(result);
				int iErrCode = jsonObject.getInt("error_code");
				if (iErrCode == CodeResults.SUCCESS) {
					JSONObject data = jsonObject.getJSONObject("data");
					// ZID_User user=ZID_CommonUtils.getUser(data);
					// ZID_CommonUtils.setSessionUser(user);
					// go2UserAcountManagementActivity();
				} else {
					_plusClient.revokeAccessAndDisconnect(LoginActivity.this);
					// String strErrMsg = ZID_ZCodeResults.getErrMsg(iErrCode);
					// Toast.makeText(ZID_Login.this, strErrMsg,
					// Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			// BEGIN: DON'T NEED GOOGLE SESSION ANYMORE => CLEAR
			_plusClient.revokeAccessAndDisconnect(LoginActivity.this);
			// END: DON'T NEED GOOGLE SESSION ANYMORE => CLEAR

			super.onPostExecute(result);

			if (_progressDialogAuthGoogleAcn.isShowing()) {
				_progressDialogAuthGoogleAcn.dismiss();
			}
		}
	}
}
